package admin

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"strconv"
	"strings"
)

type AddArticle struct {
	Id    string `json:"id"`
	Cid   string `json:"cid"`
	Title string `json:"title"`
	Text  string `json:"text"`
	Order int64  `json:"order"`
}

type ArticelListParam struct {
	Title   string `json:"title"`
	PerPage int    `json:"perPage"`
	CurPage int    `json:"curPage"`
}

type ArticleController struct {
	Ctx iris.Context
}

func (c *ArticleController) OptionsCreate() mvc.Result {
	return mvc.Response{
		Code: 204,
	}
}
func (c *ArticleController) PostCreate() interface{} {
	addArticle := AddArticle{}
	content, err := c.Ctx.GetBody()

	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal([]byte(content), &addArticle)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析参数出错:%s", err.Error()), "")
	}
	if len((addArticle.Title)) <= 0 {
		return utils.CommonRes(1000, "请输入文章标题", "")
	}
	if len(addArticle.Cid) <= 0 {
		return utils.CommonRes(1000, "请选择文章分类", "")
	}
	if len(addArticle.Text) <= 0 {
		return utils.CommonRes(1000, "请输入文章内容", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库%s", err.Error()), "")
	}

	sess := db.NewSession()

	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("事务开启失败%s", err.Error()), "")
	}
	article := new(models.Article)
	article.Title = addArticle.Title
	article.Cid = utils.Atoi64(addArticle.Cid)
	article.Text = addArticle.Text
	article.Order = addArticle.Order
	category := new(models.Category)
	_, err = sess.ID(addArticle.Cid).Get(category)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("文章%s", err.Error()), "")
	}

	_, err = sess.InsertOne(article)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("操作失败%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}
func (c *ArticleController) OptionsEdit() mvc.Result {
	return mvc.Response{
		Code: 204,
	}
}
func (c *ArticleController) PostEdit() interface{} {
	addArticle := AddArticle{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal([]byte(content), &addArticle)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析参数出错:%s", err.Error()), "")
	}
	if len(addArticle.Id) <= 0 {
		return utils.CommonRes(1000, "缺少必要参数", "")
	}
	if len(addArticle.Title) <= 0 {
		return utils.CommonRes(1000, "请输入文章标题", "")
	}
	if len(addArticle.Cid) <= 0 {
		return utils.CommonRes(1000, "请选择文章分类", "")
	}
	if len(addArticle.Text) <= 0 {
		return utils.CommonRes(1000, "请填写文章内容", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}
	sess := db.NewSession()
	article := new(models.Article)
	article.Id, _ = strconv.ParseInt(addArticle.Id, 10, 64)
	article.Cid, _ = strconv.ParseInt(addArticle.Cid, 10, 64)
	article.Title = addArticle.Title
	article.Text = addArticle.Text
	article.Order = addArticle.Order

	category := new(models.Category)
	_, err = sess.ID(addArticle.Cid).Get(category)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无效文章分类%s", err.Error()), "")
	}

	_, err = sess.Table(new(models.Article)).ID(addArticle.Id).
		Cols("title", "cid", "text").Update(article)
	if err != nil {
		return utils.CommonRes(1000, "操作失败", "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}
func (c *ArticleController) OptionsDel() mvc.Result {
	return mvc.Response{
		Code: 204,
	}
}
func (c *ArticleController) PostDel() interface{} {
	delParam := utils.DelParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接受请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &delParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}
	if len(delParam.Ids) <= 0 {
		return utils.CommonRes(1000, "缺少必要参数", "")
	}
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接服务器:%s", err.Error()), "")
	}

	ids := strings.Split(delParam.Ids, ",")
	for _, id := range ids {
		article := new(models.Article)
		db.ID(id).Get(article)
		db.ID(id).Delete(article)
	}

	return utils.CommonRes(20000, "操作成功", "")
}
func (c *ArticleController) OptionsList() mvc.Result {
	return mvc.Response{
		Code: 204,
	}
}
func (c *ArticleController) PostList() interface{} {
	articleListParam := ArticelListParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	err = json.Unmarshal([]byte(content), &articleListParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析参数出错:%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, "无法连接服务器", "")
	}
	start := (articleListParam.CurPage - 1) * articleListParam.PerPage

	sess := db.NewSession()

	if len(articleListParam.Title) > 0 {
		sess = sess.Where("title like ?", fmt.Sprintf("%%%s%%", articleListParam.Title))
	}
	conds := sess.Conds()

	articleObjList := make([]models.ArticleCategoryObj, 0)
	sess.Table("article").Alias("a").
		Join("LEFT", []string{"category", "c"}, "a.cid = c.id").
		Select("a.*, c.*").Where(conds).OrderBy("a.created desc").Limit(articleListParam.PerPage, start)

	err = sess.Find(&articleObjList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取大学列表:%s", err.Error()), "")
	}
	article := new(models.Article)
	total, err := sess.Where(conds).Count(article)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取大学列表:%s", err.Error()), "")
	}
	articleListResp := make([]models.Article, 0)
	for _, item := range articleObjList {
		art := models.Article{}
		art.Id = item.Article.Id
		art.Title = item.Article.Title
		art.Cid = item.Article.Cid
		art.CategoryName = item.Category.Name
		item.Article.Text = utils.TrimHtml(item.Article.Text)
		art.Text = utils.Substr(item.Article.Text, 0, 24)
		art.CreateTime = item.Article.Created.Format("2006-01-02 15:04:05")
		articleListResp = append(articleListResp, art)
	}
	data := map[string]interface{}{
		"total": total,
		"list":  articleListResp,
	}
	return utils.CommonRes(20000, "成功获取大学列表", data)
}
func (c *ArticleController) OptionsDetail() mvc.Result {
	return mvc.Response{
		Code: 204,
	}
}
func (c *ArticleController) PostDetail() interface{} {
	editParam := utils.EditParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &editParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(editParam.Id) <= 0 {
		return utils.CommonRes(1000, "参数不完整", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	article := new(models.Article)
	ok, err := db.ID(editParam.Id).Get(article)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("信息获取失败:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "信息获取失败", "")
	}
	if article.Cid > 0 {
		category := new(models.Category)
		_, _ = db.ID(article.Cid).Get(category)
		article.CategoryName = category.Name
	}

	return utils.CommonRes(20000, "信息获取成功", article)
}
